use sqlx::{PgPool, Error};
use struct_field_names_as_array::FieldNamesAsSlice;

use crate::core::psqlx_tools::SqlString;
use crate::model::config::ConfigModel;
use crate::model::model::Model;
use crate::types::backend::config_type::ConfigForm;


pub struct ConfigService;

impl ConfigService {
    

    /// 获取配置详情
    /// 参数 id 配置id
    /// 正确返回 ConfigForm 表单数据
    /// 错误返回 sqlx::Error
    pub async fn get_config(db: &PgPool) -> Result<ConfigForm, Error> {
        let model = ConfigModel::new();
        let sql = SqlString::new(model.table())
        .field_slice(ConfigForm::FIELD_NAMES_AS_SLICE)
        .append_primary_key()
        .where_primary_key()
        .select();

        let res = sqlx::query_as::<_, ConfigForm>(&sql)
        .bind(1)
        .fetch_one(db)
        .await;

        res
    }

    /// 更新配置
    /// 参数 data ConfigForm 表单数据
    /// 正确返回 bool true
    /// 错误返回 sqlx::Error
    pub async fn update_config(db: &PgPool, data: &ConfigForm) -> Result<bool, Error> {
        let model = ConfigModel::new();
        let sql = SqlString::new(model.table())
        .field_slice(ConfigForm::FIELD_NAMES_AS_SLICE)
        .where_primary_key()
        .update();

        let res = sqlx::query(&sql)
        .bind(1)
        .bind(&data.name)
        .bind(&data.seo_title)
        .bind(&data.seo_keywords)
        .bind(&data.seo_description)
        .execute(db)
        .await;

        match res {
            Ok(data) => Ok(data.rows_affected() > 0),
            Err(e) => Err(e)
        }
    }

}
    